package models

import (
	"api01/util"
	"errors"
	"github.com/astaxie/beego/orm"
)

type Group struct {
	Id int
	Name string
	Pid int
}

func init()  {

	orm.RegisterModel(new(Group))
}

func GetGroupAll() ([]Group , error) {
	o := orm.NewOrm()
	var groups []Group
	_, err  := o.QueryTable("group").All(&groups)
	if err != nil {
		return groups, errors.New("查询失败")
	}
	return groups , nil
}

func AddGroupOne(group *Group) error {
	o := orm.NewOrm()
	count, _ := o.QueryTable("group").Filter("pid",group.Pid).Filter("name", group.Name).Count()
	if count>0 {
		return errors.New("名称重复")
	}
	_, err := o.Insert(group)
	if err !=nil {
		util.Log.Error("group Insert err:"+err.Error())
		return errors.New("创建失败")
	}
	return nil
}

func GetGroupById(id int) (Group, error) {
	o := orm.NewOrm()
	group := Group{}
	err := o.QueryTable("group").Filter("id", id).One(&group)
	if err != nil {
		return group, errors.New("数据丢失")
	}
	return group, nil
}

func UpdateGroupById(id int, name string) error {
	o := orm.NewOrm()
	group := new(Group)
	err := o.QueryTable("group").Filter("id", id).One(group)
	if err != nil {
		return errors.New("数据丢失")
	}
	group.Name = name
	_, err = o.Update(group)
	if err != nil {
		return errors.New("修改失败")
	}
	return nil
}

func DeleteGroupById(id int) error {
	o := orm.NewOrm()
	group := new(Group)
	err := o.QueryTable("group").Filter("id", id).One(group)
	if err != nil {
		return errors.New("数据丢失")
	}
	_, err = o.Delete(group)
	if err != nil {
		return errors.New("删除失败")
	}
	return nil
}